import React, { Component } from 'react'
import {
  View,
  Text,
  TextInput,
  TouchableWithoutFeedback,
  Keyboard
} from 'react-native'

// import { NavigationActions } from 'react-navigation'

import { connect } from 'react-redux'

import StyleSheet from '../../utils/rzStyleSheet'

import {
  API_PASSWD_LOGIN
} from '../../constants/api'

import { toast, callApi } from '../../actions/app'

import { login } from '../../actions/nav'

import RzButton from '../../components/common/button'

import Validator from '../../utils/validator'

import User from '../../models/user'

import DB from '../../utils/storage'

import {
  USER_LOGIN
} from '../../constants/actionType'

const styles = StyleSheet.create({
  container: {
    justifyContent: 'flex-start',
    alignItems: 'stretch',
    backgroundColor: 'transparent',
    position: 'absolute',
    left: 0,
    right: 0,
    bottom: 0,
    top: 64
  },
  userName: {
    // flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 20,
    marginHorizontal: 20,
    height: 30
  },
  userLabel: {
    fontSize: 16,
    marginRight: 10
  },
  userNameInput: {
    flex: 1,
    borderWidth: 1,
    height: 30,
    borderRadius: 5,
    paddingHorizontal: 10,
    borderColor: '#999'
  },
  loginButton: {
    marginTop: 50,
    marginHorizontal: 30,
    borderRadius: 5,
    backgroundColor: '#aaf'
  }
})

class Login extends Component {
  constructor (props) {
    super(props)
    this.displayName = 'Login'

    this.state = {
      isloading: false,
      disabled: false,
      userNameText: '',
      passwordText: ''
    }

    this.login = this.login.bind(this)
    this.nameOnChange = this.nameOnChange.bind(this)
    this.passwordOnChange = this.passwordOnChange.bind(this)
  }

  componentWillMount () {
    DB.get('lastLoginAccount').then((lastLoginAccount) => {
      if (lastLoginAccount) {
        console.log('==lastLoginAccount===', lastLoginAccount)
        this.setState({ userNameText: String(lastLoginAccount) })
      }
    })
  }

  componentDidMount () {
    console.log('===Login==33==')
  }

  login () {
    const {
      passwordText,
      userNameText
    } = this.state
    const {
      dispatch,
      passwordLogin
    } = this.props
    const isPhoneNum = Validator.is({ type: 'mobile', input: userNameText })
    if (!isPhoneNum) {
      console.log('==!isPhoneNum==', isPhoneNum)
      dispatch(toast('error', '请输入正确手机号码！'))
      return
    }
    if (!passwordText || passwordText.length < 6) {
      dispatch(toast('error', '请输入6位以上的密码！'))
      return
    }
    this.setState({
      isloading: true,
      disabled: true
    })

    passwordLogin({
      uname: userNameText,
      password: passwordText
    }, () => {
      this.setState({
        isloading: false,
        disabled: false
      })
    })
  }

  nameOnChange (text) {
    this.setState({ userNameText: text })
  }

  passwordOnChange (text) {
    this.setState({ passwordText: text })
  }

  // <RzButton
  //   style={styles.loginButton}
  //   buttonTitle={'登录'}
  //   isloading={this.state.isloading}
  //   disabled={this.state.disabled}
  //   onPress={this.login}
  //   activityIndicatorColor={'red'}
  // />

  render () {
    return (
      <TouchableWithoutFeedback style={{ flex: 1 }} onPress={() => Keyboard.dismiss()}>
        <View style={styles.container}>
          <View style={[styles.userName, { marginTop: 50 }]}>
            <Text style={styles.userLabel}>用户名
            </Text>
            <TextInput
              style={styles.userNameInput}
              underlineColorAndroid={'transparent'}
              keyboardType={'numeric'}
              onChangeText={this.nameOnChange}
              value={this.state.userNameText}
              clearButtonMode={'while-editing'}
              placeholder={'请输入您的用户名'}
              maxLength={11}
            />
          </View>
          <View style={styles.userName}>
            <Text style={styles.userLabel}>密    码
            </Text>
            <TextInput
              style={styles.userNameInput}
              underlineColorAndroid={'transparent'}
              secureTextEntry
              onChangeText={this.passwordOnChange}
              value={this.state.passwordText}
              placeholder={'请输入您的密码'}
            />
          </View>
          <RzButton
            style={styles.loginButton}
            buttonTitle={'登录'}
            isloading={this.state.isloading}
            disabled={this.state.disabled}
            onPress={this.login}
            activityIndicatorColor={'red'}
          />
        </View>
      </TouchableWithoutFeedback>
    )
  }
}

Login.propTypes = {
}

Login.navigationOptions = {
  headerTitle: '登录',
  headerLeft: null
}

function mapStateToProps (state) {
  return {
  }
}

function mapDispatchToProps (dispatch) {
  return {
    dispatch,
    passwordLogin: (params, done) => dispatch(callApi({
      api: API_PASSWD_LOGIN,
      body: params,
      loading: true,
      success: (response) => {
        const user = new User({
          loginName: params.uname,
          userId: response.data.userId,
          epayAccount: response.data.epayAccount,
          mobile: response.data.mobile,
          email: response.data.email,
          userCode: response.data.code
        })
        DB.put('lastLoginAccount', params.uname)
        dispatch({
          type: USER_LOGIN,
          payload: { user }
        })
        user.save()
        dispatch(toast('success', '登录成功'))
        dispatch(login())
      },
      fail: (response) => {
        console.log('==res==', response)
        dispatch(toast('error', response.message))
        done()
      }
    }))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Login)
